/**
 *
 * @Explain DataTables表格
 * @Author JIAWL
 * @Date 2018/1/30 9:30
 * @version 19.01.09.01
 *
 */
(function ($) {
    'use strict';

    var WinningTable = function (el, options) {
        this.options = $.extend({language: WinningTable.Language}, WinningTable.DEFAULTS, options);
        this.$el = $(el);
        this.dataTables = null;
        this.datatable = [];
        this.datas = [];
        this.init();
    };

    WinningTable.DEFAULTS = {
        // scrollY: "300px",
        // scrollCollapse: "true",
        classes: 'table',
        select: {style: 'os'},
        // dom: "<'row'<'col-sm-6 button-toolbar'><'col-sm-6'Bf>>" +
        // "<'row'<'col-sm-12'tr>>" +
        // "<'row'<'col-sm-5 col-xs-6 'i><'col-sm-7 col-xs-6'p>>",
        // dom: '<"toolbar">frtip',
        dom: 'Bfrtip',
        buttons: [],// excel pdf  print
        pageLength: 10,
        ordering: true,
        searching: true,
        info: true,
        processing: true,
        fixedHeader: {
            headerOffset: 50
        },
        "footerCallback": function (row, data, start, end, display) {
            if (row != null) {
                var api = this.api(), data;
                var cols = [];
                for (var item in api.columns()[0]) {
                    if (api.column(item).footer().className != null && api.column(item).footer().className.indexOf("total") != -1) {
                        cols.push(item);
                    }
                }
                // Remove the formatting to get integer data for summation
                var intVal = function (i) {
                    return typeof i === 'string' ?
                        i.replace(/[\$,]/g, '') * 1 :
                        typeof i === 'number' ?
                            i : 0;
                };
                if (api.data().length > 0 && data.length > 0) {
                    if (cols.length > 0) {
                        for (var i = 0; i < cols.length; i++) {
                            // 全部合计（注：只有非后端分页是起效）
                            var total = api
                                .column(cols[i])
                                .data()
                                .reduce(function (a, b) {
                                    return intVal(a) + intVal(b);
                                }, 0);

                            // 当前页合计
                            var pageTotal = api
                                .column(cols[i], {page: 'current'})
                                .data()
                                .reduce(function (a, b) {
                                    return intVal(a) + intVal(b);
                                }, 0);

                            // 更新页脚 '$' + pageTotal + ' ( $' + total + ' total)'
                            $(api.column(cols[i]).footer()).html(Math.round(pageTotal * 100) / 100);
                        }
                    }
                } else {
                    if (cols.length > 0) {
                        for (var i = 0; i < cols.length; i++) {
                            $(api.column(cols[i]).footer()).html(0);
                        }
                    }
                }
            }
        }
    };


    WinningTable.Language = {
        sProcessing: "处理中...",
        sLengthMenu: "显示 _MENU_ 项结果",
        sZeroRecords: "没有匹配结果",
        sInfo: "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
        sInfoEmpty: "显示第 0 至 0 项结果，共 0 项",
        sInfoFiltered: "(由 _MAX_ 项结果过滤)",
        sInfoPostFix: "",
        sSearch: "搜索：",
        sUrl: "",
        sEmptyTable: "表中数据为空",
        sLoadingRecords: "载入中...",
        // old, obsolete, using sThousands instead
        sInfoThousands: ",",
        sThousands: ",",
        oPaginate: {
            sFirst: "首页",
            sPrevious: "上页",
            sNext: "下页",
            sLast: "末页"
        },
        oAria: {
            sSortAscending: ": 以升序排列此列",
            sSortDescending: ": 以降序排列此列"
        },
        select: {
            rows: {
                _: "已选择 %d 行",
                0: "点击选择行",
                1: "已选择 1 行"

            }
        }
    };

    WinningTable.prototype.init = function () {
        this.refreshDataTable(this.options);
        //$.fn.dataTable.FixedHeader(this.dataTables);
    };

    WinningTable.prototype.refreshDataTable = function (option) {
        if ($(this.$el).dataTable.isDataTable(this.$el)) {
            this.dataTables = $(this.$el).DataTable();
        } else {
            this.dataTables = $(this.$el).DataTable(option);
        }

        /*
            2019-01-09 Jiawl
            注释原因:
                工具栏不能放下拉框等其他控件*/
        // if (this.options.toolbar != null) {
        //     var toolbar = $(this.options.toolbar).clone(true);
        //     (toolbar).appendTo($(this.$el).parents(".dataTables_wrapper").find('.button-toolbar'));
        //     toolbar.removeClass("hidden");
        //     $(this.options.toolbar).addClass("hidden");
        // }



  if (this.options.toolbar != null) {

      if(HTML==undefined)
          HTML=$(this.options.toolbar).html();

      if(HTML!=undefined) {
          $(this.options.toolbar).remove();

          $(HTML).appendTo( $(this.$el).parents(".dataTables_wrapper").find('.toolbar'));
          $(this.$el).parents(".dataTables_wrapper").find('.toolbar').css('float','left')

      }
  }


    };

    var HTML=undefined;


    WinningTable.prototype.destoryDataTable = function () {
        //var optionsText = JSON.stringify(this.options);
        var tempOption = $.extend(true, {}, this.options);
        this.dataTables.destroy();
        this.options = tempOption;//JSON.parse(optionsText);
    };

    //querydata
    WinningTable.prototype.queryDataInPage = function (ajaxurl, reqdatas) {
        this.destoryDataTable();
        this.draw();
        var queryOption = {
            serverSide: true,
            ajax: function (data, callback, settings) {
                var reqParams = {
                    pageSize: data.length,
                    start: data.start,
                    search: data.search.value
                };

                var params = $.extend(reqParams, reqdatas);

                $.post(ajaxurl, params, function (res) {
                    callback({
                        recordsTotal: res.totalSize,
                        recordsFiltered: res.totalSize,
                        data: res.datas
                    });
                });
            }
        };
        queryOption = $.extend(queryOption, this.options);
        this.refreshDataTable(queryOption);
    };
    WinningTable.prototype.queryData = function (ajaxurl, reqdatas,afterSuccess) {
        this.destoryDataTable();
        this.draw();
        var $this = this;
        var queryOption = {
            ajax: function (data, callback, settings) {
                $.post(ajaxurl, reqdatas, function (res) {
                    if (!res.success) {
                        swal("发生错误", res.errorMsg, "error");
                        callback({
                            recordsTotal: 0,
                            data: []
                        });
                        return;
                    }
                    $this.reloadDataTable(res.datas);
                    if (res.datas == null || res.datas.length == 0) {
                        this.datas = [];
                        callback({
                            recordsTotal: 0,
                            data: []
                        });
                        return;
                    }
                    // $this.reloadDataTable(res.datas);
                    callback({
                        recordsTotal: res.datas.length,
                        data: res.datas
                    });
                    if(afterSuccess!=null){
                        afterSuccess({
                            recordsTotal: res.datas.length,
                            data: res.datas
                        });
                    }
                });
            }
        };
        queryOption = $.extend(queryOption, this.options);
        this.refreshDataTable(queryOption);
    };

    WinningTable.prototype.reloadInitDataTable = function(datas){
        this.destoryDataTable();
        this.draw();
        // this.reloadDataTable(datas);
        this.options.datas = datas;
        this.options.recordsTotal = datas.length;
        this.refreshDataTable(this.options);
    }

    WinningTable.prototype.reloadDataTable = function (datas) {
        this.datas = datas;
        var options = {primaryKey: this.options.primaryKey};
        this.initDataTable(datas);
    };

    WinningTable.prototype.initDataTable = function (data) {
        this.datatable = new DataTable(data, this.options);
    };

    WinningTable.prototype.getSelectedDatas = function () {
        return this.dataTables.rows({selected: true}).data();
    };

    WinningTable.prototype.getSelectedRows = function () {
        return this.dataTables.rows({selected: true});
    };

    WinningTable.prototype.draw = function () {
        return this.dataTables.draw();
    };

    WinningTable.prototype.destroy = function () {
        return this.dataTables.destroy();
    };

    WinningTable.prototype.setDataSource = function (datas) {
        this.destoryDataTable();
        var queryOption = $.extend(true, queryOption, this.options);
        queryOption.data = datas;
        this.datas = datas;
        this.refreshDataTable(queryOption);
    };

    $.fn.winningTable = function (option) {
        var $this = $(this);
        return new WinningTable($this, option);
    }

})(jQuery);